package com.inspection.service.impl;

import com.google.common.collect.Lists;
import com.inspection.config.LoginConstant;
import com.inspection.constant.UserStatusEnum;
import com.inspection.dao.SysUserDao;
import com.inspection.entity.InspectionEventDO;
import com.inspection.entity.SysUserDO;
import com.inspection.model.dto.LoginDTO;
import com.inspection.model.vo.LoginVO;
import com.inspection.service.LoginService;
import com.inspection.support.AssertUtils;
import com.inspection.support.auth.JwtHelper;
import com.inspection.support.auth.SecretConstant;
import com.inspection.support.model.BusinessBaseException;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SysUserDao sysUserDao;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginVO doLogin(LoginDTO login) {

        AssertUtils.nonNull(login.getLoginAccount(),"账号不能为空");
        AssertUtils.nonNull(login.getLoginPwd(),"密码不能为空");

        Specification<SysUserDO> specification = (Specification<SysUserDO>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = Lists.newArrayList();
            predicates.add(criteriaBuilder.equal(root.get("isDel"), 0));

            predicates.add(criteriaBuilder.or(
                            criteriaBuilder.equal(root.get("userName"), login.getLoginAccount()),
                            criteriaBuilder.equal(root.get("userCode"), login.getLoginAccount()),
                            criteriaBuilder.equal(root.get("mobile"), login.getLoginAccount())));

            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Optional<SysUserDO> sysUserOp = sysUserDao.findOne(specification);

        if(!sysUserOp.isPresent()){
            throw new BusinessBaseException("账号不存在！");
        }


        SysUserDO user = sysUserOp.get();
        //是否禁用
        if(UserStatusEnum.NORMAL.getStatus()!=user.getUserStatus()){
            throw new BusinessBaseException("账号已禁用！");
        }

        if(!user.getPassword().equals(DigestUtils.md5Hex(login.getLoginPwd()+ LoginConstant.LOGIN_SALT))){
            throw new BusinessBaseException("密码错误！");
        }

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("userCode",user.getUserCode());
        paramMap.put("realName",user.getRealName());

        String token = JwtHelper.generateJWT(user.getId().toString(), user.getUserName(), SecretConstant.DATAKEY_USER, paramMap);
        LoginVO vo = new LoginVO();
        SysUserDO userRes = new SysUserDO();
        userRes.setId(user.getId());
        userRes.setUserCode(user.getUserCode());
        userRes.setUserName(user.getUserName());
        userRes.setRealName(user.getRealName());
        vo.setToken(token);
        vo.setUser(userRes);
        return vo;
    }
}
